grErp.controller('DingjiaCtrl',['$scope','$filter','inventoryFactory','DingjiaFactory','subProFactory',function($scope,$filter,inventoryFactory,DingjiaFactory,subProFactory){
    var sellspecmodal=$("#sellspecmodal");
    var promodal=$("#promodal");
    var modal=$("#exampleModal");
    $scope.dingjiainit=function(){
        DingjiaFactory.ajaxGetPreDingjiaBatchList().then(function(d){
            $scope.preDingjiaBatchList=d;
        })
    }
    $scope.preDingjiaBatchSelect=function(batch){
        DingjiaFactory.ajaxGetPreDingjiaBatchGoods(batch).then(function(d){
            $scope.preDingjiaBatchGoods=d;
            angular.forEach($scope.preDingjiaBatchGoods,function(data){
                data.total_num=$filter('strToNum')(data.total_num)
                data.unit_num_price=$filter('strToNum')(data.unit_num_price)
                data.total_weight=$filter('strToNum')(data.total_weight)
                data.unit_weight_price=$filter('strToNum')(data.unit_weight_price)
                data.unit_box_fee=$filter('strToNum')(data.unit_box_fee)
                data.unit_box_weight=$filter('strToNum')(data.unit_box_weight)
                data.trans_fee=$filter('strToNum')(data.trans_fee)
                data.percent=$filter('strToNum')(data.percent)
                data.loss=$filter('strToNum')(data.loss)
                data.cost_off=$filter('strToNum')(data.cost_off)
            })
        })
    }
    $scope.calculate=function(){
        angular.forEach($scope.preDingjiaBatchGoods,function(data,index){
            var calculateTypeArr=JSON.parse(data.type_json);
            $scope.preDingjiaBatchGoods[index].calculateTypeArr=simplieToChinese(calculateTypeArr);
            $scope.preDingjiaBatchGoods[index].calculateTypeSelected=$scope.preDingjiaBatchGoods[index].calculateTypeArr[0].calculateType
            var calculateType=calculateTypeArr[0];
            $scope.preDingjiaBatchGoods[index].calculateType=calculateType;
            priceObj=calculateFormulary(data,calculateType);
            data.base_price=priceObj.base_price;
            data.sg_base_price=priceObj.sg_price;
        })
        $scope.items=$scope.preDingjiaBatchGoods;
    }
    $scope.changeCalculateTpe=function(index,type){
        console.log($scope.items[index].calculateTypeArr)
        var data=calculateFormulary($scope.preDingjiaBatchGoods[index],type);
        $scope.preDingjiaBatchGoods[index].calculateType=type;
        $scope.items[index].base_price=data.base_price;
    }
    /**
     * 英文方式转中文计算方式
     * @param arr
     * @returns {Array}
     */
    simplieToChinese=function(arr){
        var outArr=[];
        angular.forEach(arr,function(data,index){
            switch(data){
                case 'jmjm':
                    outArr.push({calculateType:'jmjm',CN:'斤卖斤卖',selected:index==0?true:false})
                    break;
                case 'xmjm':
                    outArr.push({calculateType:'xmjm',CN:'箱卖斤卖',selected:index==0?true:false})
                    break;
                case 'xmgm':
                    outArr.push({calculateType:'xmgm',CN:'箱卖个卖',selected:index==0?true:false})
                    break;
                case 'jmgm':
                    outArr.push({calculateType:'jmgm',CN:'斤卖个卖',selected:index==0?true:false})
                    break;
            }
        })
        return outArr;
    }
    /**
     * 成本计算公式
     * @param data
     * @param type
     * @returns {{}}
     */
    calculateFormulary=function(data,type){
        var p = data;
        var out_put={};
        switch (type){
            case 'jmjm':
                //  (总重*斤价+箱*（箱费+运费）-优惠)/((总重-箱数*皮重)*(1-报损)*食用率)
                var price = (p.total_weight* p.unit_weight_price+ p.total_num*(p.trans_fee+ p.unit_box_fee)-p.cost_off)/((p.total_weight-p.unit_box_weight*p.total_num)*(1-p.loss)*p.percent);
                var unit='斤'
                var sg_price=(p.total_weight* p.unit_weight_price+ p.total_num*(p.trans_fee+ p.unit_box_fee)-p.cost_off)/ p.total_num;
                var sg_unit=$filter('getLaterUnit')(p.erp_spec);
                out_put.base_price=price.toFixed(1)+'元/'+unit;
                out_put.sg_price=sg_price.toFixed(1)+'元/'+sg_unit;
                return out_put;
                break;
            case 'xmjm':
                //  (箱*箱价-优惠)/((总重-箱数*皮重)*(1-报损)*食用率)
                var price = (p.total_num*( p.unit_num_price+p.trans_fee+ p.unit_box_fee)-p.cost_off)/((p.total_weight-p.unit_box_weight*p.total_num)*(1-p.loss)*p.percent);
                var unit='斤'
                var sg_price= (p.total_num*( p.unit_num_price+p.trans_fee+ p.unit_box_fee)-p.cost_off)/ p.total_num;
                var sg_unit=$filter('getLaterUnit')(p.erp_spec);
                out_put.base_price=price.toFixed(1)+'元/'+unit;
                out_put.sg_price=sg_price.toFixed(1)+'元/'+sg_unit;
                return out_put;
                break;
            case 'xmgm':
                //    （箱价-优惠/箱数）-/（每箱个数*(1-报损)）
                var unit_num=$filter('strToNum')(p.erp_spec);
                var price= (p.total_num*(p.unit_num_price+p.trans_fee+ p.unit_box_fee)-p.cost_off)/(p.total_num*unit_num* (1-p.loss));
                var unit=$filter('getSpecUnit')(p.erp_spec);
                var sg_price=(p.total_num*(p.unit_num_price+p.trans_fee+ p.unit_box_fee)-p.cost_off)/p.total_num
                var sg_unit=$filter('getLaterUnit')(p.erp_spec);
                out_put.base_price=price.toFixed(1)+'元/'+unit;
                out_put.sg_price=sg_price.toFixed(1)+'元/'+sg_unit;
                return out_put;
                break;
            case 'jmgm':
                //    ((总斤*斤价-优惠)/箱数)/（每箱个数*(1-报损)）
                var unit_num=$filter('strToNum')(p.erp_spec);
                var price= (p.total_weight* p.unit_weight_price+p.total_num*(p.trans_fee+ p.unit_box_fee)- p.cost_off)/( p.total_num*unit_num* (1-p.loss));
                var unit=$filter('getSpecUnit')(p.erp_spec);
                var sg_price=(p.total_weight* p.unit_weight_price+p.total_num*(p.trans_fee+ p.unit_box_fee)- p.cost_off)/p.total_num
                var sg_unit=$filter('getLaterUnit')(p.erp_spec);
                out_put.base_price=price.toFixed(1)+'元/'+unit;
                out_put.sg_price=sg_price.toFixed(1)+'元/'+sg_unit;
                return out_put;
                break;
        }
    }
    $scope.remove=function($index){
        if(confirm("确定删除该条?")){
            $scope.items.splice($index, 1)
        }
    }
    /**
     * 规格定价
     */
    $scope.sellproductinit=function(){
        $scope.specproduct=[];
        inventoryFactory.getproductlist('zj').then(function(d){
            $scope.sellproductlist=d;
        });
        DingjiaFactory.getallbatch(3).then(function(d){
            $scope.batchlist=d;
        });
        subProFactory.ajaxGetSubproInventoryProductList().then(function(d){
            $scope.subprolist=d;
        });

    }
    /**
     * 定价规格新增
     */
    $scope.addSellSpec=function(){
        sellspecmodal.modal();
        promodal.modal();
        $("#sellspecform").get(0).reset();
        $scope.sellproduct={
            base_price:0,
            multi_num:1,
            gr_trans_fee:0,
            process_fee:0,
            subpro:[{
                subpro_num:1
            }]
        }
    }
    $scope.sellprodcutselect=function(index){
        var selectproduct=$scope.sellproductlist[index];
        $scope.sellproduct.BIN=selectproduct.BIN;
        $scope.sellproduct.pname=selectproduct.pname;
        $scope.sellproduct.spec=selectproduct.spec;
    }
    /**
     * 定价批次选择
     * @param batch
     */
    $scope.basebatchselect=function(batch){
        DingjiaFactory.getlist(batch).then(function(d){
            $scope.baseproductlist=d;
        });
    }
    /**
     * 定价商品选择
     * @param index
     */
    $scope.baseproductselect=function(index){
        $scope.sellproduct.base_price=$filter('strToNum')($scope.baseproductlist[index].base_price);
    }
    /**
     * 定价耗材添加
     */
    $scope.subproadd=function(){
        $scope.sellproduct.subpro.push(
            {subpro_num:1}
        );
    }
    /**
     * 定价耗材删除
     * @param index
     */
    $scope.subproremove=function(index){
        if(confirm("确定删除该条?")){
            $scope.sellproduct.subpro.splice(index,1);
        }
    }
    /**
     * 定价计算
     */
    $scope.spec_count_price=function(){
        var specproduct=$scope.sellproduct;
        var package_fee=0
        angular.forEach(specproduct.subpro,function(row){
            package_fee=package_fee+parseInt(row.subpro_num)*parseFloat(row.subpro_unit_price);
        })
        if(isNaN(specproduct.base_price)){
            alert("基础成本有误");
            return;
        }
        if(isNaN(specproduct.multi_num)){
            alert("规格倍数有误");
            return;
        }
        if(isNaN(specproduct.process_fee)){
            alert("手工成本有误");
            return;
        }
        if(isNaN(specproduct.gr_trans_fee)){
            alert("快递成本有误");
            return;
        }
        if(isNaN(package_fee)){
            alert("耗材输入有误");
            return;
        }
        var spec_price_sc=specproduct.base_price*1.2*parseInt(specproduct.multi_num)+specproduct.gr_trans_fee+specproduct.process_fee+package_fee;
        var spec_price_yg=specproduct.base_price*1.15*parseInt(specproduct.multi_num)+specproduct.process_fee+package_fee;
        var spec_price_gyd=specproduct.base_price*1.05*parseInt(specproduct.multi_num)+specproduct.process_fee+package_fee;
        var spec_price_gyds=specproduct.base_price*1.4*parseInt(specproduct.multi_num)+specproduct.process_fee+package_fee;
        var spec_price_qsy=specproduct.base_price*1.2*parseInt(specproduct.multi_num)+specproduct.process_fee+package_fee;
        var spec_price_pf=specproduct.base_price*1.25*parseInt(specproduct.multi_num)+specproduct.process_fee+package_fee;
        var spec_product_counted={
            batch:specproduct.batch,
            pname:specproduct.pname,
            spec:specproduct.spec,
            BIN:specproduct.BIN,
            base_price:specproduct.base_price,
            multi_num:specproduct.multi_num,
            gr_trans_fee:specproduct.gr_trans_fee,
            process_fee:specproduct.process_fee,
            package_fee:package_fee,
            spec_price_sc:spec_price_sc.toFixed(2),
            spec_price_yg:spec_price_yg.toFixed(2),
            spec_price_gyd:spec_price_gyd.toFixed(2),
            spec_price_gyds:spec_price_gyds.toFixed(2),
            spec_price_qsy:spec_price_qsy.toFixed(2),
            spec_price_pf:spec_price_pf.toFixed(2)
        }
        $scope.specproduct.push(spec_product_counted);
        sellspecmodal.modal('hide');
    }
    $scope.autospecpriceinit=function(batchid,batch){
        loadingStart();
        var specList=[];
        var specInfo={noZj:0};
        async.waterfall([
            function(done){
                if($filter('isValidValue')(batch)){
                    DingjiaFactory.AjaxGetBasePriceByBatch(batch).then(function(d){
                        done(null,d);
                    })
                }else if($filter('isValidValue')(batchid)){
                    DingjiaFactory.AjaxGetBasePriceById(batchid).then(function(d){
                        done(null,d);
                    });
                }
            },
            function(list,done){
                specInfo.ybzLength=list.length;
                angular.forEach(list,function(data,index){
                    var BIN='2'+data.BIN.substr(1,4);
                    var unit=$filter('getLaterUnit')(data.base_price)
                    var price=$filter('strToNum')(data.base_price)
                    DingjiaFactory.AjaxGetZjList(BIN,unit).then(function(sublist){
                        if(sublist.length==0){
                            specInfo.noZj++;
                        }
                        angular.forEach(sublist,function(data2){
                            var times=$filter('strToNum')(data2.spec);
                            data2.priceNoFee=parseFloat(times*price).toFixed(2);
                            specList.push(data2);
                        });
                        done(null,3);
                    })
                });
            },
            //计算价格
            function(f2,done){
                angular.forEach(specList,function(data,index){
                    DingjiaFactory.AjaxGetSellPrice(data.priceNoFee,data.BIN).then(function(d){
                        specList[index].subpro_fee=parseFloat(d.subpro_fee);
                        specList[index].process_fee=parseFloat(d.process_fee);
                        specList[index].trans_fee=parseFloat(d.trans_fee);
                        specList[index].sellprice=parseFloat(specList[index].priceNoFee)+parseFloat(d.subpro_fee)+parseFloat(d.process_fee)+parseFloat(d.trans_fee);
                        //商城售价
                        specList[index].spec_price_sc=1.2*specList[index].priceNoFee+parseFloat(d.subpro_fee)+parseFloat(d.process_fee)+parseFloat(d.trans_fee);
                        //果饮店售价
                        specList[index].spec_price_gyd=1.05*specList[index].priceNoFee+parseFloat(d.subpro_fee)+parseFloat(d.process_fee);
                        //员工售价
                        specList[index].spec_price_yg=1.15*specList[index].priceNoFee+parseFloat(d.subpro_fee)+parseFloat(d.process_fee);
                        //企事业单位售价
                        specList[index].spec_price_qsy=1.2*specList[index].priceNoFee+parseFloat(d.subpro_fee)+parseFloat(d.process_fee);
                        //批发售价
                        specList[index].spec_price_pf=1.25*specList[index].priceNoFee+parseFloat(d.subpro_fee)+parseFloat(d.process_fee);
                        //广源丁山售价
                        specList[index].spec_price_gyds=1.4*specList[index].priceNoFee+parseFloat(d.subpro_fee)+parseFloat(d.process_fee);
                        if(specList.length==(index+1)){
                            done(null,3);
                        }else{
                            return;
                        }
                    })
                })
            }
        ],function(err,result){
            if(err){
                loadingEnd();
            }else{
                $scope.specproduct=specList;
                specInfo.total=specList.length;
                $scope.specInfo=specInfo;
                loadingEnd();
            }
        });
    }
    $scope.getspecprice=function(list){

    }
    $scope.basepricequicksave=function(index){
        DingjiaFactory.ajaxPostQuickBasePriceSave($scope.items[index]).then(function(d){
            if(d==1){
                alert("保存成功");
            }else{
                alert("保存失败");
            }
        })
    }
}]);
grErp.factory('DingjiaFactory',['$http','$q',function($http,$q){
    var service={};
    /**
     *ajax获取基础定价预处理批次列表
     * @returns {*}
     */
    service.ajaxGetPreDingjiaBatchList=function(){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Caigouer/ajaxGetPreDingjiaBatchList",
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    }
    /**
     * ajax获取基础定价预处理批次商品
     * @returns {*}
     */
    service.ajaxGetPreDingjiaBatchGoods=function(batch){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Caigouer/ajaxGetPreDingjiaBatchGoods",
            params:{batch:batch}
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    }
    /**
     * 获取批次对应商品
     * @param batch
     * @returns {*}
     */
    service.getlist=function(batch){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Dingjia/ajaxGetBasePrice",
            params:{batch:batch}
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    }
    /**
     * 获取所有批次
     * @param limit
     * @returns {*}
     */
    service.getallbatch=function(limit){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Dingjia/ajaxgetallbatch",
            params:{limit:limit}
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    }
    /**
     * 获取批次对应批次信息
     * @param batch
     * @returns {*}
     */
    service.getbatchinfo=function(batch){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Dingjia/ajaxgetbatchinfo",
            params:{batch:batch}
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    }
    /**
     * 关联商品操作
     * @param pname
     * @param spec
     * @returns {*}
     */
    service.bindgood=function(pname,spec){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Caigouer/ajaxbindgood",
            params:{pname:pname,spec:spec}
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    }
    /**
     * 删除批次定价商品
     * @param id
     * @returns {*}
     */
    service.delbatchgood=function(id){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Dingjia/ajaxdelbatchgood",
            params:{id:id}
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    }
    /**
     * ajax通过id获取商品基础价格
     * @param id
     * @returns {*}
     * @constructor
     */
    service.AjaxGetBasePriceById=function(id){
        var q=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Dingjia/AjaxGetBasePriceById",
            params:{id:id}
        }).success(function(data){
            q.resolve(data);
        }).error(function(err){
            q.reject(err);
        })
        return q.promise;

    }
    /**
     * ajax获取正价商品列表
     * @param BIN
     * @param unit
     * @returns {*}
     * @constructor
     */
    service.AjaxGetZjList=function(BIN,unit){
        var q=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Dingjia/AjaxGetZjList",
            params:{BIN:BIN,unit:unit}
        }).success(function(data){
            q.resolve(data);
        }).error(function(err){
            q.reject(err);
        })
        return q.promise;

    }
    /**
     * ajax获取包装费，运输费，消耗品信息
     * @param priceNoFee
     * @param BIN
     * @returns {*}
     * @constructor
     */
    service.AjaxGetSellPrice=function(priceNoFee,BIN){
        var q=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Dingjia/AjaxGetSellPrice",
            params:{priceNoFee:priceNoFee,BIN:BIN}
        }).success(function(data){
            q.resolve(data);
        }).error(function(err){
            q.reject(err);
        })
        return q.promise;
    }

    service.AjaxGetBasePriceByBatch=function(batch){
        var q=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Dingjia/AjaxGetBasePriceByBatch",
            params:{batch:batch}
        }).success(function(data){
            q.resolve(data);
        }).error(function(err){
            q.reject(err);
        })
        return q.promise;
    }
    service.ajaxPostQuickBasePriceSave=function(data){
        var q=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Dingjia/ajaxPostQuickBasePriceSave",
            params:{data:data}
        }).success(function(data){
            q.resolve(data);
        }).error(function(err){
            q.reject(err);
        })
        return q.promise;
    }
    return service;

}]);
